package com.cjack.frenchexcel.service;

import com.cjack.frenchexcel.dao.RechargeRecordDao;
import com.cjack.frenchexcel.dao.RecuPersoDao;
import com.cjack.frenchexcel.dao.UserDao;
import com.cjack.frenchexcel.model.RecuPersoModel;
import com.cjack.frenchexcel.table.RechargeRecordTable;
import com.cjack.frenchexcel.table.RecuPersoTable;
import com.cjack.frenchexcel.util.ModelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class RecuPersoService {

    @Autowired
    private RecuPersoDao dao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private RechargeRecordDao rechargeRecordDao;

    public List< RecuPersoModel> list( RecuPersoModel model){
        Sort sort = new Sort( Sort.Direction.DESC, "createTime");
        Example< RecuPersoTable> example = Example.of( ModelUtils.copySignModel( model, RecuPersoTable.class));
        return ModelUtils.copyListModel( dao.findAll( example, sort), RecuPersoModel.class);
    }

    public void save( RecuPersoModel model){
        RecuPersoTable table;
        if( !StringUtils.isEmpty( model.getJobNumber())){
            model.setUserId( userDao.getOneByJobNumber( model.getJobNumber()).getId());
        }
        if( model.getId() == null){//新增，把model里面的属性全部复制到新的table里面
            table = ModelUtils.copySignModel( model, RecuPersoTable.class);
        }else{//修改，把model里面的[非空]属性赋值到数据库里面查询的table里面
            table = dao.findOne( model.getId());
            ModelUtils.copySignModel( model, table);
            if( "1".equals( model.getStatus())){//如果是设置手动充值表的到帐状态，则需要同步设置到充值记录表
                RechargeRecordTable rechargeRecordTable = rechargeRecordDao.getBySourceFromAndOtherId( "RECUPERSO_TRIGGER", model.getId());
                rechargeRecordTable.setMoneyStatus( "6");
                if( rechargeRecordTable.getUpdateMoneyStatusOne() == null){
                    rechargeRecordTable.setUpdateMoneyStatusOne( new Date());
                }
                if( rechargeRecordTable.getUpdateMoneyStatusTwo() == null){
                    rechargeRecordTable.setUpdateMoneyStatusTwo( new Date());
                }
                if( rechargeRecordTable.getUpdateMoneyStatusThree() == null){
                    rechargeRecordTable.setUpdateMoneyStatusThree( new Date());
                }
                rechargeRecordTable.setUpdateTime( new Date());
                rechargeRecordDao.save( rechargeRecordTable);
            }
        }
        dao.save( table);
    }
}
